package cn.sh.org.service.impl;

import cn.sh.basic.page.PageList;
import cn.sh.basic.service.impl.BaseServiceImpl;
import cn.sh.org.domain.Department;
import cn.sh.org.mapper.DepartmentMapper;
import cn.sh.org.query.DepartmentQuery;
import cn.sh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 业务逻辑处理
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    //查询所有信息
    @Override
    public List<Department> selectAll() {
        return departmentMapper.selectAll();
    }

    @Override
    public Department selectOne(Long id) {
        return departmentMapper.selectOne(id);
    }

    //添加信息
    @Override
    @Transactional
    public void add(Department department) {
        departmentMapper.add(department);
        this.update(department);
    }

    //修改信息
    @Override
    @Transactional
    public void update(Department department) {
        if (department.getParent()==null){
            String dirPath = "/" + department.getId();
            department.setDirPath(dirPath);
        }else {
            Long parentId = department.getParent().getId();
            Department parent = departmentMapper.selectOne(parentId);
            department.setDirPath(parent.getDirPath() + "/" + department.getId());
        }
        departmentMapper.update(department);
    }

    //删除信息
    @Override
    @Transactional
    public void delete(Long id) {
        departmentMapper.delete(id);
    }

    @Override
    @Transactional
    public void batchDelete(List ids) {
        departmentMapper.batchDelete(ids);
    }

    @Override
    public List<Department> getTree() {
        List<Department> all = departmentMapper.selectAll();//获取所有部门
        List<Department> result = new ArrayList<>();//声明返回的集合 里面装一级部门

        HashMap<Long, Department> hashMap = new HashMap<>();
        for (Department department : all) {
            hashMap.put(department.getId(),department);
        }

        for (Department temp : all) {
            if (temp.getParent_id() == null){//一级部门
                result.add(temp);
            }else {//非一级部门
                Long parent_id = temp.getParent_id();/*获取部门的父部门id*/
                Department parent = hashMap.get(parent_id);/*根据父部门id拿到父部门对象*/
                parent.getChildren().add(temp);
            }
        }

        return result;
    }
}
